package com.AnywheeBt;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.ArrayList;
import java.util.List;


import android.os.Binder;
import android.os.IBinder;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import com.AnywheeBt.bean.BtContact;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.text.format.Time;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.content.res.Resources;

import static com.AnywheeBt.BtCallBack.oneshot;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadsetClient;
import android.bluetooth.BluetoothHeadsetClientCall;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAvrcpController;
import android.bluetooth.BluetoothAvrcp;
import android.bluetooth.BluetoothA2dpSink;


import com.AnywheeBt.PbapClient.BluetoothPbapClient;
import com.AnywheeBt.PbapClient.utils.BTConfig;
import com.AnywheeBt.PbapClient.utils.Utils;
import com.AnywheeBt.bean.BtContact;
import com.AnywheeBt.IAvrcpControllerDataCb;


import com.android.vcard.VCardEntry;
import com.AnywheeBt.DatabaseHelper;

/*
 * BTService
 */
public class BTService extends Service implements com.AnywheeBt.SzhBAction.AnywheeBtActionListener {
	private static final String TAG = "BTService";
	private static final int CLOSE_PHONE = 100;
	private static final int OPEN_PHONE = 200;
	private static final int START_BT = 300;
	private static final int MSG_MUTE = 0;
	private static final int MSG_UNMUTE = 1;
	private static final int MSG_INSERT_CONTACTS = 2;
	private static final int MSG_UPDATE_CONTACT_PROVIDER = 3;
	private static final int MSG_SYNC_DEL_ALL_CONTACTS = 4;
	private static final int MSG_CALLING_CHECK = 25;
	private static final int MSG_NEW_CALLING = 26;
	private static final int AVRCP_CT_DATA_RESPONSE = 400;
	
	private boolean bBtCallPhone = false;
	private boolean bBtState = false;
	private boolean bBtStart = false;
	private boolean bNetworkService = false;
	private BluetoothDevice btDevice = null;
	private BluetoothDevice btSinkDevice = null;
	private int		btHfpState  = 0;
	private BluetoothDevice	btHfpDevice = null;
	private String strBtName = "";
	private int callState = BluetoothHeadsetClientCall.CALL_STATE_TERMINATED;

	private MediaPlayer mMediaPlayer = null;
	private SharedPreferences prefs;
	private PbCallList BookList;
	static BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
	private BluetoothHeadsetClient mHeadSetClientService;
	private BluetoothAvrcpController mAvrcpClientService;
	private BluetoothA2dpSink mA2dpSinkService;
	public static  BluetoothPbapClient  pbapClient =null;
	private PbapHandler mHandler = new PbapHandler();

	public static  boolean  btServiceRuning =false;
	
	public static  int  btAudioStat = 0;


	public final static String SURFACE = "surface";

	private Handler mCtHandler = null;

	IAvrcpControllerDataCb.Stub mBinder;
	private  AudioManager mAudioManager = null;//zqg 0304
	//private Handler mCtHandler = null;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			String str = msg.getData().getString("msgstr");
			Log.e(TAG, "msgstr=" + str + " id=" + msg.what);
			
			//msg
			switch (msg.what) {
				case OPEN_PHONE:
					OpenCallView(str);
					break;
				case CLOSE_PHONE:
					CloseBTView();
					break;
				case START_BT:
					if (false == bBtStart) {
						bBtStart = true;
					}
					break;
				case MSG_MUTE:
					setStreamMute(true);
					break;
				case MSG_UNMUTE:
					setStreamMute(false);
					break;
				case MSG_INSERT_CONTACTS:

					break;
				case MSG_UPDATE_CONTACT_PROVIDER:

					break;
				case MSG_SYNC_DEL_ALL_CONTACTS:
				
					break;
			    //
				case MSG_NEW_CALLING:

					break;
				//
				case MSG_CALLING_CHECK:	{
					break;
				}
				default:
					break;	
			}
		super.handleMessage(msg);
		}
	};
	
	private boolean isPlayingBefore = false;
	private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            
            //启动翼卡
            if(Utils.ACTION_NAVI_CALL_ECAR.equals(action)){
            	
            }else if(Utils.AIOS_ANDROID_BT_GETBLTSTATUS.equals(action)){
            	/*接收到aios查询蓝牙连接广播，发送当前蓝牙连接状态给aios*/
            	if(SzhBAction.GetBtState()){
            		Intent intentBtconnect = new Intent();
    				intentBtconnect.setAction(BTConfig.BT_CONNECTED);
    				context.sendBroadcast(intentBtconnect);
    				//Log.e("=======Yanglin=======", "BtReceiver  action = " + "com.android.bt.connected");
            	}else{
            		Intent intentBtdisconnect = new Intent();
    				intentBtdisconnect.setAction(BTConfig.BT_DISCONNECTED);
    				context.sendBroadcast(intentBtdisconnect);
    				//Log.e("=======Yanglin=======", "BtReceiver  action = " + "com.android.bt.disconnected");
            	}
            }else if("audiomanager.intent.action.MUSIC_PLAY".equals(action)
                    || "audiomanager.intent.action.AIOS_MUSIC_PLAY".equals(action)
                    ||"audiomanager.intent.action.VIDEO_PLAY".equals(action)
){
            		//设置蓝牙音量为最低，此处最好暂停音乐
            		mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, 0, AudioManager.FLAG_SHOW_UI);
            }else if("audiomanager.intent.action.MUSIC_PAUSE".equals(action)
                    ||"audiomanager.intent.action.AIOS_MUSIC_PAUSE".equals(action)
                    ||"audiomanager.intent.action.VIDEO_PAUSE".equals(action)
){
            		//设置蓝牙音量为最高,此处最好播放蓝牙音乐
        			mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, 15, AudioManager.FLAG_SHOW_UI);
            }else if(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_START.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_START.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_START.equals(action)){  
            		//设置蓝牙音量为最低
        			mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, 0, AudioManager.FLAG_SHOW_UI);
            }else if(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_STOP.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_STOP.equals(action) 
            		|| Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_STOP.equals(action)){
            		//设置蓝牙音量为最高
        			mAudioManager.setStreamVolume(AudioManager.STREAM_BLUETOOTH_SCO, 15, AudioManager.FLAG_SHOW_UI);
            }
        }
    };
	
	@Override
    public IBinder onBind(Intent intent) {
    	Log.e(TAG, "onBind**** "+mBinder);
        return mBinder;
    }
	
	//Binder object: Must be static class or memory leak may occur
    private static class AvrcpControllerDataCbBinder extends IAvrcpControllerDataCb.Stub{
        private BTService mService;


        AvrcpControllerDataCbBinder(BTService svc) {
            mService = svc;
        }


        public void cdDataResponseCb(byte[] data,int len){
            Log.i(TAG,"Binder Call: cdDataResponseCb "+data[0]);
            if(mService == null) return;
            if(mService.mCtHandler != null)
				mService.mCtHandler.obtainMessage(AVRCP_CT_DATA_RESPONSE, len, 0, data).sendToTarget();
        }

    };
    
    //
    public void onDataReceive(String cmd){

    	needMute(cmd);
//    	/** NOT CONNECTED */
//    	if(cmd.equals(Command.RECEIVE_NOT_CONNECTED)){
//
//    	}else if(cmd.equals(Command.RECEIVE_CONNECTED)){
//   
//    	}
//    	/** Phone */
//        else if(cmd.startsWith(Command.RECEIVE_START_OUTGOING)){
//   
//       }else if(cmd.startsWith(Command.RECEIVE_START_INCOMING)){
//    	   
//       }
//		/** HFState */
//		else if(cmd.startsWith(Command.RECEIVE_HF_STATUS)){
//	
//		}
//    	/** HANGUP */
//		else if (cmd.equals(Command.RECEIVE_HANGUP_PHONE)) {
//	
//		}
//		/** DTMF */
//		else if(cmd.startsWith(Command.RECEIVE_START_ECAR_DTMF)){
//
//		} 	
//    	/** ADDRESS */
//		else if(cmd.startsWith(Command.RECEIVE_START_BTADDRESS)){
//
//		}   	
//    	/** UPLOAD CONTACTS AND RECORD */
//    	else if (cmd.startsWith(Command.RECEIVE_START_UPLOAD_PHONEBOOK)) {
//
//        }else if (cmd.equals(Command.RECEIVE_UPLOAD_PHONEBOOK_END)) {
//
//        }
//        /*suzhen playing music*/
//        else if(cmd.startsWith(Command.RECEIVE_PLAYING_MUSIC)){
//
//        }else if(cmd.startsWith(Command.RECEIVE_PAUSE_MUSIC)){
//        }
//    	/** Pair list */
//        else if(cmd.startsWith(Command.RECEIVE_START_PAIR)){
//
//        }
    }
	
    //
    private void needMute(String cmd){
//		if(BTManager.IsBtWifiCombo)	return;
//    	if (cmd.equals(Command.RECEIVE_HF_STATUS_OUTGOING)//cmd.equals(Command.RECEIVE_HF_STATUS_INCOMING)||
//				||cmd.equals(Command.RECEIVE_HF_STATUS_ONGOING)
//				) {//||cmd.equals(Command.RECEIVE_START_INCOMING
//			//mHandler.removeMessages(MSG_UNMUTE);
//			mHandler.sendEmptyMessage(MSG_MUTE);
//			Log.i(TAG,"<><><>---蓝牙打电话中发送静音消息--------->");
//		}else if (cmd.equals(Command.RECEIVE_HANGUP_PHONE)){
//			mHandler.removeMessages(MSG_NEW_CALLING);   //suzhen
//			mHandler.removeMessages(MSG_CALLING_CHECK);
//			mHandler.sendEmptyMessage(MSG_UNMUTE);
//			Log.i(TAG,"<><><>---蓝牙挂断电话发送取消静音消息--------->");
//		}
    }
    
	//
    private synchronized void setStreamMute(boolean mute){
//    	if(mAudioManager == null)
//    		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//    	boolean currentMute = mAudioManager.isMasterMute();
//    	if(currentMute == mute){
//    		return;
//    	}
//    	mAudioManager.setMasterMute(mute,0);
    }
		
	//
	public void SavePhone(String str) {
		if (str == "")
			return;
		Time time = new Time(); // or Time t=new Time("GMT+8");
		time.setToNow();
		time.month = time.month + 1;
		String strTime = String.format("%02d-%02d %02d:%02d:%2d", time.month,
				time.monthDay, time.hour, time.minute, time.second);
		PbCallList pb_list = new PbCallList();
		pb_list.get_list(PbCallList.BT_PB_LIST);
		String strName = " ";
		int pos = pb_list.FindListofNum(str);
		if (pos > 0) {
			strName = pb_list.GetListName(pos);
			if (strName != "" && mMainLayout != null) {
				((TextView) mMainLayout.findViewById(R.id.bt_name))
						.setText(strName);
			}
		}
		PbCallList call_list = new PbCallList();
		call_list.get_list(PbCallList.BT_CALL_LIST);
		call_list.SetList(strName, str, strTime, "" + bBtCallPhone, 0);
		call_list.Save_List(PbCallList.BT_CALL_LIST);
	}
	
	@Override
	public void onCreate() {
		Log.i(TAG, "onCreate");
		bBtCallPhone = false;
		btServiceRuning = true;
		//*KmlParse kmlParse = new KmlParse(null);
		//*String strTemp = kmlParse.readKmlName("CarRecord/defaultpara/bt_uart/");
		//*if (strTemp == null || strTemp == "")
		//*	strDevName = strTemp;
		//*newMediaPlayer("/system/media/audio/bt.ogg");

		handler.sendEmptyMessageDelayed(START_BT, 5000);
		SzhBAction.SetActionListener(this);
		//*OpenBtPower();
		mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET_CLIENT);
		mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.AVRCP_CONTROLLER);
		mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.A2DP_SINK);


		mBinder=new AvrcpControllerDataCbBinder(this);
		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);//zqg 0304
		IntentFilter filter = new IntentFilter();
		filter.addAction(Utils.ACTION_NAVI_CALL_ECAR);
		filter.addAction(Utils.AIOS_ANDROID_BT_GETBLTSTATUS);
	//	filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_START);
	//	filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INTERRUPT_STOP);
//		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_START);
//		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_AIOS_STOP);
//		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_START);
//		filter.addAction(Utils.AUDIOMANAGER_INTENT_ACTION_INSERT_STOP);
	//	filter.addAction("audiomanager.intent.action.AIOS_MUSIC_PLAY");
	//	filter.addAction("audiomanager.intent.action.AIOS_MUSIC_PAUSE");
	//	filter.addAction("audiomanager.intent.action.VIDEO_PAUSE");
	//	filter.addAction("audiomanager.intent.action.VIDEO_PLAY");
	//	filter.addAction("audiomanager.intent.action.MUSIC_PAUSE");
	//	filter.addAction("audiomanager.intent.action.MUSIC_PLAY");
        registerReceiver(receiver, filter);
		super.onCreate();
	}
	
	//
	private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() {
		//
		public void onServiceConnected(int profile, BluetoothProfile proxy) {
			Log.i(TAG, "******onServiceConnected profile:" + profile);
			if (profile == BluetoothProfile.HEADSET_CLIENT)
				mHeadSetClientService = (BluetoothHeadsetClient) proxy;
			else if(profile == BluetoothProfile.AVRCP_CONTROLLER)
				mAvrcpClientService = (BluetoothAvrcpController) proxy;
			else if(profile == BluetoothProfile.A2DP_SINK)
				mA2dpSinkService = (BluetoothA2dpSink) proxy;


			if (mHeadSetClientService != null){
				List<BluetoothDevice> deviceList = mHeadSetClientService.getConnectedDevices();
				if (!deviceList.isEmpty()){
					for (BluetoothDevice dev : deviceList){
						 SetBtState(true,dev);
						 SetBtName(dev.getName());
						 break;
					}
				}
				else{
					Log.i(TAG,"device null***********");
				}
			}
		}
		
		//
		public void onServiceDisconnected(int profile) {  
			if (profile == BluetoothProfile.HEADSET_CLIENT) {	
				mHeadSetClientService = null;  
			}else if(profile == BluetoothProfile.AVRCP_CONTROLLER)
				mAvrcpClientService = null;
			else if(profile == BluetoothProfile.A2DP_SINK)
				mA2dpSinkService = null;
		}  
	};
	
	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		unregisterReceiver(receiver);
		SzhBAction.SetActionListener(null);
		CloseBTView();
		//*StopUart();
		//*CloseBtPower();
		//*ChangeBtAudio(false);

		mAdapter.closeProfileProxy(BluetoothProfile.HEADSET_CLIENT,mHeadSetClientService);
		mAdapter.closeProfileProxy(BluetoothProfile.AVRCP_CONTROLLER,mAvrcpClientService);
		mAdapter.closeProfileProxy(BluetoothProfile.AVRCP_CONTROLLER,mA2dpSinkService);
		
		btServiceRuning = false;

		bBtStart = false;
		mBinder = null;
		super.onDestroy();
	}
	
	//
	private boolean bBlState = false;
	private WindowManager mWindowManager;
	private WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
	private LinearLayout mMainLayout;
	public void CreateBTView(int x, int y, int width, int height, String str) {
		Log.i(TAG, "CreateBTView A");
		Intent mIntent = new Intent("com.anywhee.HOMERECEIVER");
		mIntent.putExtra("home", "bl_on");
		sendBroadcast(mIntent);
		if (mMainLayout != null) {
			return;
		}
		
		//
		mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
		wmParams.type = LayoutParams.TYPE_PHONE; // TYPE_SYSTEM_ALERT;
		wmParams.format = PixelFormat.RGB_888; // RGBA_8888;
		wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
		wmParams.gravity = Gravity.LEFT | Gravity.TOP;
		wmParams.x = x;
		wmParams.y = y;
		wmParams.width = width;
		wmParams.height = height;
	}

	public void CloseBTView() {
		Log.i(TAG, "CloseBTView");
		bBtCallPhone = false;
		if (mMainLayout != null) {
			mWindowManager.removeView(mMainLayout);
			mMainLayout = null;
		}
		
		Intent intentp = new Intent();
		intentp.setAction("com.AnywheeBt.PbList"); 			
		intentp.putExtra("Pb", "2");
		sendBroadcast(intentp);
//		 Intent mIntent = new Intent("com.anywhee.HOMERECEIVER");
//		 mIntent.putExtra("home","bl_on");
//		 sendBroadcast(mIntent);
	}

	@Override
	public int SyncCallPb(int target, int offset, int count) {
		int ret = -1;
		return ret;
	}

	@Override
	public int CallPhone(String number) {
		int ret = -1;
		Log.i(TAG,"********CallPhone:"+number);
		if(mHeadSetClientService != null && btDevice != null){
			if(mHeadSetClientService.dial(btDevice,number) == true){
				ret = 0;
			}
			//
			Intent intent = new Intent();
			intent.setClass(BTService.this, BtCallBack.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.putExtra("strNumber", number);
			intent.putExtra("isDialout", true);
			startActivity(intent);
		}else{
			Log.i(TAG,"********CallPhone no sevice");
		}
		//
		if (ret < 0){
			Toast.makeText(BTService.this,
					getResources().getString(R.string.msg_connect_error), 3)
					.show();
		}
		return ret;
	}

	@Override
	public int SetCmdBt(String strCmd, int delay) {
		int ret = -1;
		return ret;
	}

	@Override
	public int SetCmdBtPara(String strCmd, String para, int delay) {
		int ret = -1;
		return ret;
	}

	@Override
	public void OpenCallView(String str) {
		Resources r = getResources();
		float btn_x = r.getDimension(R.dimen.BTview_x);
		float btn_y = r.getDimension(R.dimen.BTview_y);
		float btn_w = r.getDimension(R.dimen.BTview_w);
		float btn_h = r.getDimension(R.dimen.BTview_h);
		CreateBTView((int) btn_x, (int) btn_y, (int) btn_w, (int) btn_h, str);
	}

	@Override
	public boolean GetBtState() {
		return bBtState;
	}
	
	@Override
	public boolean SetBtState(boolean btState,BluetoothDevice dev) {
		bBtState = btState;
		btDevice = dev;
		if(btState == false){
			SetBtName("");
			SetNetWorkService(false);
			callState = BluetoothHeadsetClientCall.CALL_STATE_TERMINATED;
		}
		Intent mIntent = new Intent("com.anywheeBt.BTMAINRECIVER");
		mIntent.putExtra("main_str", "bt_state");
		sendBroadcast(mIntent);
		return true;
	}

	@Override
	public boolean GetNetWorkService() {
		return bNetworkService;
	}
	
	@Override
	public boolean SetNetWorkService(boolean netWork) {
		bNetworkService = netWork;
		return true;
	}

	@Override
	public String GetBtName() {
		return strBtName;
	}
	
	@Override
	public  String    GetBtAddress(){
		if(btDevice == null)return "";
		return btDevice.getAddress();
	}
	
	@Override
	public void SetBtName(String btName ) {
		Log.e(TAG, "*********SetBtName" + btName);
		strBtName = btName;
		Intent mIntent = new Intent("com.anywheeBt.BTMAINRECIVER");
		mIntent.putExtra("main_str", "bt_name");
		sendBroadcast(mIntent);
	}
	
	@Override
	public String GetLocalBtName() {
		return mAdapter.getName();
	}
	
	@Override
	public void SetLocalBtName(String btName ) {
		Log.e(TAG, "*********SetLocalBtName" + btName);
		mAdapter.setName(btName);
	}

	@Override
	public boolean GetBtStartState() {
		return bBtStart;
	}
	
	@Override
	public  void SetBtPassThroughCmd(int keyCode, int keyState){
		Log.e(TAG, "*********SetBtPassThroughCmd:" + mAvrcpClientService);
		if(mAvrcpClientService != null && btDevice != null){
			Log.e(TAG, "*********SetBtPassThroughCmd keyCode:" + keyCode);
			mAvrcpClientService.sendPassThroughCmd(btDevice,keyCode,keyState);
		}
	}
	@Override
	public  void hangupCall(){
		Log.e(TAG, "*********hangupCall");
		if(mHeadSetClientService != null && btDevice != null){
			mHeadSetClientService.rejectCall(btDevice);
		}
	}
	
	@Override
	public	void terminateCall(){
		Log.e(TAG, "*********terminateCall");
		if(mHeadSetClientService != null && btDevice != null){
			mHeadSetClientService.terminateCall(btDevice,0);
		}
	}
	
	@Override
	public	void acceptCall(){
		Log.e(TAG, "*********acceptCall");
		if(mHeadSetClientService != null && btDevice != null){
			mHeadSetClientService.acceptCall(btDevice,BluetoothHeadsetClient.CALL_ACCEPT_NONE);
		}
	}

	@Override
	public  boolean   ConnectA2dpSinkDevice(BluetoothDevice dev){
		Log.e(TAG, "*********ConnectA2dpSinkDevice :"+mA2dpSinkService);
		if(mA2dpSinkService == null)
			return false;
		return mA2dpSinkService.connect(dev);
	}
	@Override
	public  boolean   DisConnectA2dpSinkDevice(BluetoothDevice dev){
		Log.e(TAG, "*********DisConnectA2dpSinkDevice :"+mA2dpSinkService);
		if(mA2dpSinkService == null)
			return false;
		return mA2dpSinkService.disconnect(dev);
	}
	@Override
	public  boolean   ConnectHfpclientDevice(BluetoothDevice dev){
		Log.e(TAG, "*********ConnectHfpclientDevice :"+mHeadSetClientService);
		if(mHeadSetClientService == null)
			return false;
		return mHeadSetClientService.connect(dev);
	}
	@Override
	public  boolean   DisConnectHfpclientDevice(BluetoothDevice dev){
		Log.e(TAG, "*********disConnectHfpclientDevice :"+mHeadSetClientService);
		if(mHeadSetClientService == null)
			return false;
		return mHeadSetClientService.disconnect(dev);
	}
	@Override
	public  void   SetBtA2dpSinkState(boolean btState,BluetoothDevice dev){
		btSinkDevice = dev;
	}
	@Override
	public  void      setBtHfpclientState(int btState,BluetoothDevice dev){
		btHfpState = btState;
		btHfpDevice = dev;
	}
	@Override
	public  int getBtHfpclientState(){
		return btHfpState;
	}
	@Override
	public  BluetoothDevice getBtHfpclientDevice(){
		return btHfpDevice;
	}
	@Override
	public void StartIncomingActivity(String num){
		Intent acintent = new Intent();
		acintent.setClass(BTService.this, BtCallBack.class);
		acintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		acintent.putExtra("strNumber", num);
		acintent.putExtra("isDialout", false);
		startActivity(acintent);
	}


		@Override
	public void setCallState(int state){
		callState = state;
	}
	@Override
	public int getCallState(){
		return callState;
	}
	@Override
	public void sendDTMF(String number){
		if(mHeadSetClientService != null && number != null){
			byte[] bytes = number.getBytes();
			mHeadSetClientService.sendDTMF(btDevice,bytes[0]);
		}
	}
	@Override
	public  void      setCtHandler(Handler handler){
		mCtHandler = handler;
	}
	@Override
	public  void connectAudio(){
		if(mHeadSetClientService != null)
			mHeadSetClientService.connectAudio();
	}
	@Override
	public  void disConnectAudio(){
		if(mHeadSetClientService != null)
			mHeadSetClientService.disconnectAudio();
	}
	//
	private class PbapHandler extends Handler {
		DatabaseHelper mDatabaseHelper;
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            mDatabaseHelper = DatabaseHelper.getDatabaseHelper(BTService.this);
            super.handleMessage(msg);
			Log.i(TAG,"PbapHandler**msg.what:"+msg.what);
            switch (msg.what) {
			case 2://EVENT_PULL_PHONE_BOOK_DONE
				mDatabaseHelper.delAllNumber();
				ArrayList<VCardEntry> req = (ArrayList<VCardEntry>) msg.obj;
				String number;
				for(VCardEntry entry:req){
					number = "null";        
					if(entry.getPhoneList() != null && entry.getPhoneList().size() >= 1)
						number = entry.getPhoneList().get(0).getNumber();
					number = number.replace("-","");
		       		Log.i("card","card****:" + entry.getNameData().getFamily()+" num:"+number);
					String name = entry.getNameData().getFamily() + entry.getNameData().getMiddle()+entry.getNameData().getGiven();
				 	Log.i(TAG,"insert devAddr***********:" + btDevice.getAddress());
					mDatabaseHelper.insertContact(btDevice.getAddress(), name, number);
				}
			
				Intent intentp = new Intent();
				intentp.setAction("com.AnywheeBt.PbList"); 		
				intentp.putExtra("Pb", "1");
				sendBroadcast(intentp);
				pbapClient.disconnect();
				pbapClient = null;
				break;
			case 201://EVENT_SESSION_CONNECTED
					Intent intentp1 = new Intent();
					intentp1.setAction("com.AnywheeBt.PbList"); 		
					intentp1.putExtra("Pb", "2");
					sendBroadcast(intentp1);
				break;
			case 202://EVENT_SESSION_DISCONNECTED
					pbapClient = null;
				break;
			case 102://EVENT_PULL_PHONE_BOOK_ERROR
				if(pbapClient != null){
					Intent intentp2 = new Intent();
					intentp2.setAction("com.AnywheeBt.PbList"); 		
					intentp2.putExtra("Pb", "3");
					sendBroadcast(intentp2);
					
					pbapClient.disconnect();
					pbapClient = null;
				}
				break;
            default:
                break;
            }
        }
    }
	
	@Override
	public boolean	getPbap() {
		PbapHandler mHandler = new PbapHandler();
		Log.i(TAG,"getPbap btDevice:"+btDevice);
		if(mHeadSetClientService != null && btDevice != null){
			if(pbapClient == null)
			 	pbapClient = new BluetoothPbapClient(btDevice, mHandler);
			 pbapClient.connect();
			 pbapClient.pullPhoneBook(BluetoothPbapClient.PB_PATH,
				BluetoothPbapClient.VCARD_ATTR_VERSION | BluetoothPbapClient.VCARD_ATTR_N | BluetoothPbapClient.VCARD_ATTR_TEL,
				BluetoothPbapClient.VCARD_TYPE_21,500,0);
			return true;
		}
		return false;
	}
	
	//
	void newMediaPlayer(String file) {
		mMediaPlayer = new MediaPlayer();
		try {
			mMediaPlayer.setDataSource(file);
			mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mMediaPlayer.prepare();
		} catch (IllegalStateException e) {
			Log.e(TAG, "newMediaPlayer error");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(TAG, "newMediaPlayer error");
			e.printStackTrace();
		}
	}
	@Override
	public List<BtContact> queryPeoplesByName(String name, String s) {
		return DatabaseHelper.getDatabaseHelper(this).queryPeoplesByName(name, s);
	}
}
